#!/usr/bin/python
# -*- coding: utf8 -*-

import re
from pysqlite2 import dbapi2 as sqlite
from Dater import Dater

class Database(object):
   def __init__(self):
      self.connection = None
      self.dbpath = './db/agsf.s3db'

   def Cursor(self, force = False):
      if not force:
         if not self.connection:
            self.connection = sqlite.connect(self.dbpath)
         return self.connection.cursor()
      else:
         con = connection = sqlite.connect(self.dbpath)
         cur = connection.cursor()
         return con, cur 

   def Append_daters(self, daters):
      connection, cursor = self.Cursor(True)
      for dater in daters:
         dater.Append(cursor)
      connection.commit()

   def getDaters(self, count):
      connection, cursor = self.Cursor(True)
      cursor.execute('SELECT id, login, oid, rating from Dater')
      data = cursor.fetchmany(count)
      connection.close()
      daters = []
      if len(data):
         for d in data:
            dater = Dater()
            dater.id, dater.login, dater.oid, dater.rating = d
            daters.append(dater)
      return daters

   def Apply(self):
      self.connection.commit()

   def getLonely_(self):
      connection, cursor = self.Connect(True)
      for dater in daters:
         self.getDater_interlocutors()
         dater.Append(cursor)
      connection.commit()

   def Dater_by_login(self, cursor, login):
      cursor.execute('SELECT id, login, oid, rating from Dater WHERE login="%s"' % (login))
      data = cursor.fetchone()
      if len(data):
         self.id, self.login, self.oid, self.rating = data
         return True
      else:
         return False

   def Login_exists(self, cursor, login):
      cursor.execute('SELECT id from Dater WHERE login=?', (login,))
      data = cursor.fetchone()
      if data:
         return True
      else:
         return False

   def Dater_in_db(self, cursor):
      cursor.execute('SELECT id from Dater WHERE login = "%s"' % (self.login))
      data = cursor.fetchone()
      if data:
         return True
      else:
         return False

   def getDater_interlocutors(self, dater):
      interlocutors = []
      if self.db:
         self.db.execute('SELECT userid from Conversation WHERE daterid="%d"' % (dater.id))
         data = self.db.fetchall()
         if len(data):
            for line in data:
               user = User()
               if user.fromID(line[0]):
                  interlocutors.append(user)
      return interlocutors

def main():
   pass

if __name__ == '__main__':
   main()